<?php
/**
 * 地产服务类
 */

namespace app\index\service;

use Config;
use Cache;
use think\Db;
use app\common\library\Payment;

class Landed
{

    //地产首页轮播
    protected static $ad_type = [
        '1' => '主页轮播图',
        '2' => '地产主页轮播图',
        '3' => '地产主页广告位一',
        '4' => '地产主页广告位二',
        '5' => '地产主页广告位三',
        '6' => '楼盘主页轮播',
        '7' => '楼盘主页广告位一',
        '8' => '楼盘主页广告位二',
        '9' => '楼盘主页广告位三',
        '10' => '二手房主页轮播图',
        '11' => '二手房主页广告位一',
        '12' => '二手房主页广告位二',
        '13' => '二手房主页广告位三',
        '14' => '租房主页轮播图',
        '15' => '租房房主页广告位一',
        '16' => '租房房主页广告位二',
        '17' => '租房房主页广告位三',
    ];

    //楼盘分类
    protected static $property_category = [
        0 => ['name' => '热门精选', 'value' => 'type_1'],
        1 => ['name' => '热盘关注', 'value' => 'is_hot'],
        2 => ['name' => '最新开盘', 'value' => 'create_time'],
        3 => ['name' => '优惠买房', 'value' => 'is_preferential'],
    ];

    //二手房分类
    protected static $sh_category = [
        0 => ['name' => '二手房', 'value' => 'type_2'],
        1 => ['name' => '普通住宅', 'value' => '1'],
        2 => ['name' => '商业类', 'value' => '2'],
        3 => ['name' => '别墅', 'value' => '3'],
        4 => ['name' => '四合院', 'value' => '4'],
        5 => ['name' => '车位', 'value' => '5'],
        6 => ['name' => '其他', 'value' => '6'],
    ];
    //租房分类
    protected static $renting_category = [
        0 => ['name' => '租房', 'value' => 'type_3'],
        1 => ['name' => '住宅', 'value' => '1'],
        2 => ['name' => '别墅', 'value' => '2'],
        3 => ['name' => '公寓', 'value' => '3'],
        4 => ['name' => '商铺', 'value' => '4'],
        5 => ['name' => '写字楼', 'value' => '5'],
    ];
    //店铺分类
    protected static $shop_category = [
        0 => ['name' => '楼盘', 'value' => '1'],
        1 => ['name' => '二手房', 'value' => '2'],
        2 => ['name' => '租房', 'value' => '3'],
    ];

    //楼盘资源分类
    protected static $property_resource = [
        0 => ['name' => '视频', 'value' => '1'],
        1 => ['name' => '楼盘图', 'value' => '2'],
        2 => ['name' => '沙盘图', 'value' => '3'],
        3 => ['name' => '位置图', 'value' => '4'],
        4 => ['name' => '售楼图', 'value' => '5'],
        5 => ['name' => '楼盘证照', 'value' => '6'],
    ];

    //二手房资源分类
    protected static $second_house_resource = [
        0 => ['name' => '视频', 'value' => '1'],
        1 => ['name' => '户型图', 'value' => '2'],
        2 => ['name' => '房源图', 'value' => '3'],
        3 => ['name' => '效果图', 'value' => '4'],
        4 => ['name' => 'VR', 'value' => '5'],
    ];

    //二手房资源分类
    protected static $renting_resource = [
        0 => ['name' => '视频', 'value' => '1'],
        1 => ['name' => '户型图', 'value' => '2'],
        2 => ['name' => '房源图', 'value' => '3'],
        3 => ['name' => '效果图', 'value' => '4'],
        4 => ['name' => 'VR', 'value' => '5'],
    ];


    protected static $map_api_key = '82f7655a38a8bbb43ca63b75c0d05973';


    /**
     * @return array
     * 获取首页接口
     */
    public function getHomeAd()
    {
        $ad = Db::table('zh_ad')->where('type',1)->order('sort DESC')->field('name,thumb,target,type')->select();
        $ad = self::setThumb($ad,1);
        return $ad;
    }


    /**
     * 地产主页
     */
    public function index($city)
    {
        //获取地产首页广告数据
        $ad = Db::table('zh_ad')->where('type', 'in', '2,3,4,5')->order('sort DESC')->field('name,thumb,target,type')->select();
        $ad = self::setThumb($ad);
        if (!empty($ad)) {
            foreach ($ad as $k => $v) {
                $ads[$v['type']][] = $v;
            }
        }

        //品牌馆
        $shop = Db::table('zh_store')->where(['status' => '1'])->order('createtime DESC')->limit(64)->field('id,name,logo')->select();
        $shop = $this->setThumb($shop, 0);

        //楼盘精选
        $property_category = self::$property_category;
        $property = Db::table('zh_landed_property')->where('is_delete', 0)->where('status',1)->where("region", "like", "%" . $city . "%")->order('create_time DESC')->limit(12)->field('id,name,avg_price,thumb,region,total_amount,tag_id')->select();
        $property = $this->setThumb($property);
//        foreach ($property as &$row)
//        {
//            $row['type'] = 1;
//            if(isset($row['tag_id']) && !empty($row['tag_id'])){
//                $row['tag_id'] = explode(',',$row['tag_id']);
//            }
//            $row['comment'] = $this->getCommentStartCountByGoodsId($row['id'],$row['type']);
//        }
        //二手房精选
        $sh_category = self::$sh_category;
        $second_house = Db::table('zh_landed_second_house')->where('is_delete', 0)->where("region", "like", "%" . $city . "%")->order('create_time DESC')->limit(12)->field('id,name,thumb,unit_price,total_amount,address')->select();
        $second_house = $this->setThumb($second_house);

        //租房
        $renting_category = self::$renting_category;
        $renting = Db::table('zh_landed_renting')->where('is_delete', 0)->where('region', "like", "%" . $city . "%")->order('create_time DESC')->field('id,name,thumb,rent,address')->select();
        $renting = $this->setThumb($renting);

        return ['ad' => $ads, 'shop' => $shop, 'property' => $property, 'second_house' => $second_house, 'renting' => $renting, 'property_category' => $property_category, 'sh_category' => $sh_category, 'renting_category' => $renting_category];
    }


    /**
     * @param $type
     * @param $city
     * @param $page
     * @param $page_size
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取楼盘/二手房/租房
     */
    public function getMainIndex($type, $city, $page, $page_size, $param, $cate, $price, $room,$room_size = '',$cate_info = '')
    {
        switch ($type) {
            case 1:
                $field = 'id,name,avg_price,thumb,region,total_amount,address,tag_id';
                $ad = Db::table('zh_ad')->where('type', 'in', '6,7,8,9')->order('sort DESC')->field('name,thumb,target,type')->select();
                $db = Db::table('zh_landed_property');
                //筛选分类
                if (!empty($cate)) {
                    if ($cate != 'create_time' && $cate != 'type_1') {
                        $db->where($cate, 1);
                    }
                }elseif(!empty($cate_info)){
                    if ($cate_info != 'create_time' && $cate != 'type_1') {
                        $db->where($cate, 1);
                    }
                }
                //筛选价格
                if (!empty($price)) {
                    $price = explode('_', $price);
                    if ($price[1] != -1) {
                        $db->whereBetween('avg_price', [$price[0], $price[1]]);
                    } else {
                        $db->where('avg_price', '>', $price[0]);
                    }
                }
                //筛选面积
                if(!empty($room_size)){
                    $room_size = explode('_', $room_size);
                    if ($room_size[1] != -1) {
                        $db->whereBetween('build_surface', [$room_size[0], $room_size[1]]);
                    } else {
                        $db->where('build_surface', '>', $room_size[0]);
                    }
                }

                $category = self::$property_category;

                break;
            case 2:
                $field = 'id,name,thumb,unit_price,total_amount,address,house,room_size,orientations,village_name';
                $ad = Db::table('zh_ad')->where('type', 'in', '10,11,12,13')->order('sort DESC')->field('name,thumb,target,type')->select();
                $db = Db::table('zh_landed_second_house');
                //筛选分类
                if (!empty($cate)) {
                    if ($cate != 'type_2') {
                        $db->where('purpose', $cate);
                    }
                }elseif(!empty($cate_info)){
                    if ($cate_info != 'type_2') {
                        $db->where('purpose', $cate_info);
                    }
                }
                //筛选价格
                if (!empty($price)) {
                    $price = explode('_', $price);
                    if ($price[1] != -1) {
                        $db->whereBetween('unit_price', [$price[0], $price[1]]);
                    } else {
                        $db->where('unit_price', '>', $price[0]);
                    }
                }
                //筛选面积
                if(!empty($room_size)){
                    $room_size = explode('_', $room_size);
                    if ($room_size[1] != -1) {
                        $db->whereBetween('room_size', [$room_size[0], $room_size[1]]);
                    } else {
                        $db->where('room_size', '>', $room_size[0]);
                    }
                }
                if (!empty($room)) {
                    $db->where('house', 'like', '%' . $room . '%');
                }
                $category = self::$sh_category;
                break;

            case 3:
                $field = 'id,name,thumb,rent,address,house,room_size,orientations,village_name';
                $ad = Db::table('zh_ad')->where('type', 'in', '14,15,16,17')->order('sort DESC')->field('name,thumb,target,type')->select();
                $db = Db::table('zh_landed_renting');
                //筛选分类
                if (!empty($cate)) {
                    if ($cate != 'type_3') {
                        $db->where('house_type', $cate);
                    }
                }elseif(!empty($cate_info)){
                    if ($cate_info != 'type_3') {
                        $db->where('purpose', $cate_info);
                    }
                }
                //筛选价格
                if (!empty($price)) {
                    $price = explode('_', $price);
                    if ($price[1] != -1) {
                        $db->whereBetween('rent', [$price[0], $price[1]]);
                    } else {
                        $db->where('rent', '>', $price[0]);
                    }
                }
                //筛选面积
                if(!empty($room_size)){
                    $room_size = explode('_', $room_size);
                    if ($room_size[1] != -1) {
                        $db->whereBetween('room_size', [$room_size[0], $room_size[1]]);
                    } else {
                        $db->where('room_size', '>', $room_size[0]);
                    }
                }
                if (!empty($room)) {
                    $db->where('house', 'like', '%' . $room . '%');
                }
                $category = self::$renting_category;
        }
        if (!empty($ad)) {
            $ad = $this->setThumb($ad);
            foreach ($ad as $k => $v) {
                $ads[$v['type']][] = $v;
            }
        }
        if (!empty($param['area']) && isset($param['area'])) {
            $city .= '市/' . $param['area'];
        }
        if (!empty($param['metro']) && isset($param['metro'])) {
            $db->where('metro', $param['metro']);
        }
        //筛选距离不分页
        if (!empty($param['distance']) && isset($param['distance']) && !empty($param['latlng'])) {
            $distance = $param['distance'];
            $latlng = explode('_', $param['latlng']);
        } else {
            $db->limit(($page - 1) * $page_size, $page_size);

        }

        $list = $db->where('is_delete', 0)
            ->where("region", "like", "%" . $city . "%")
            ->where('status',1)
            ->order('create_time DESC')
            ->field($field)
            ->select();

        //根据距离筛选最近的楼盘
        if (!empty($distance) && is_array($latlng) && !empty($list)) {
            foreach ($list as $key => &$row) {
                $address = trim(str_replace('/', '', $row['region']) . $row['address']);
                $map_api = "https://restapi.amap.com/v3/geocode/geo?address=" . $address . "&output=json&key=" . self::$map_api_key;
                $api_res = file_get_contents($map_api);
                if (!empty($api_res)) {
                    $res_latlng = json_decode($api_res, true);
                    $res_latlng = $res_latlng['geocodes'][0]['location'];
                    $res_latlng = explode(',', $res_latlng);
                    $diff = $this->GetDistance($latlng[0], $latlng[1], $res_latlng[0], $res_latlng[1], 2);
                    if ($diff > $distance) {
                        unset($list[$key]);
                    }
                }
            }
            $list = array_slice($list, ($page - 1) * $page_size, $page_size);
        }
        $list = $this->setThumb($list, 0);
        foreach ($list as &$row)
        {
            $row['type'] = $type;
            if(isset($row['tag_id']) && !empty($row['tag_id'])){
                $row['tag_id'] = explode(',',$row['tag_id']);
            }
            $row['comment'] = $this->getCommentStartCountByGoodsId($row['id'],$row['type']);
        }
        return ['ad' => $ads, 'list' => $list, 'category' => $category];
    }


    /**
     * @param $type
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取楼盘/二手房/租房详情
     */
    public function getInfo($type,$id,$member_id)
    {
        switch ($type) {
            case 1:
                $data = Db::table('zh_landed_property')->where('id', $id)->where('status',1)->select()[0];
                if (!empty($data['tag_id'])) {
                    $data['tag_id'] = explode(',', $data['tag_id']);
                }
                $data['engineering_img'] = Db::table('zh_landed_property_resource')->where('propertie_id', $data['id'])->where('type', 1)->select();
                $data['engineering_img'] = $this->setThumb($data['engineering_img'], 0);
                $data['apartment_img'] = Db::table('zh_landed_property_room')->where('property_id', $data['id'])->field('id,room_sn,thumb,tag_id,orientation,room_num')->select();
                $data['apartment_img'] = $this->setThumb($data['apartment_img'], 0);
                $data['others_img'] = Db::table('zh_landed_property_resource')->where('propertie_id', $data['id'])->where('type', '<>', 1)->select();
                $data['others_img'] = $this->setThumb($data['others_img'], 0);

                $field = 'id,name,avg_price,thumb,region,total_amount,address';
                $data['recommend'] = Db::table('zh_landed_property')->where('id > '.$id)->field($field)->limit(5)->select();
                break;
            case 2:
                $data = Db::table('zh_landed_second_house')->where('id', $id)->select()[0];
//                $data['thumb'] = 'http://'.$_SERVER['HTTP_HOST'].'/'.$data['thumb'];
                $data['thumb'] = 'http://yijiahoutai.40b876.cn/yijia_store_admin/public' . $data['thumb'];
                if (!empty($data)) {
                    $data['others_img'] = Db::table('zh_landed_second_house_resource')->where('second_id', $data['id'])->where('type', 'in', '2,3,4')->select();
                    $data['others_img'] = $this->setThumb($data['others_img'], 0);
                }
                $field = 'id,name,thumb,unit_price,total_amount,address';
                $data['recommend'] = Db::table('zh_landed_second_house')->where('id > '.$id)->field($field)->limit(5)->select();

                break;
            case 3:
                $data = Db::table('zh_landed_renting')->where('id', $id)->select()[0];
                if (!empty($data['house_config'])) {
                    $data['house_config'] = explode(',', $data['house_config']);
                }
                $data['thumb'] = 'http://yijiahoutai.40b876.cn/yijia_store_admin/public' . $data['thumb'];
                if (!empty($data)) {
                    $data['others_img'] = Db::table('zh_landed_renting_resource')->where('second_id', $data['id'])->where('type', 'in', '2,3,4')->select();
                    $data['others_img'] = $this->setThumb($data['others_img'], 0);
                }
                $field = 'id,name,thumb,rent,address';
                $data['recommend'] = Db::table('zh_landed_renting')->where('id > '.$id)->field($field)->limit(5)->select();

                break;
        }

        if(!empty($member_id)){
            $member_collection = Db::table('zh_member_collection')->where('goods_id', $id)->where('type', $type)->where('member_id',$member_id)->where('is_deleted',0)->select();
            $data['is_collection'] = $member_collection ? 1 : 0;
        }else{
            $data['is_collection'] = 0;
        }
        if(!empty($data['recommend'])){
            $data['recommend'] = $this->setThumb($data['recommend'],0);
        }

        $data['latlng'] = $this->getLatLng($data['region'], $data['address']);
        return $data;
    }


    /**
     * @param $type
     * @param $id
     * @param int $resource
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取资源
     */
    public function getResource($type, $id, $resource = 1)
    {
        switch ($type) {
            case 1:
                $resource = self::$property_resource;
//                $resource = Db::table('zh_landed_property_resource')->where('propertie_id',$id)->where('type',$resource)->select();
                foreach ($resource as &$row) {
                    $row['list'] = Db::table('zh_landed_property_resource')->where('propertie_id', $id)->where('type', $row['value'])->select();
                    $row['list'] = $this->setThumb($row['list'], 0);
                }
                break;
            case 2:
                $resource = self::$second_house_resource;
//                $resource = Db::table('zh_landed_property_resource')->where('propertie_id',$id)->where('type',$resource)->select();
                foreach ($resource as &$row) {
                    $row['list'] = Db::table('zh_landed_second_house_resource')->where('second_id', $id)->where('type', $row['value'])->select();
                    $row['list'] = $this->setThumb($row['list'], 0);
                }
                break;
            case 3:
                $resource = self::$renting_resource;
//                $resource = Db::table('zh_landed_property_resource')->where('propertie_id',$id)->where('type',$resource)->select();
                foreach ($resource as &$row) {
                    $row['list'] = Db::table('zh_landed_renting_resource')->where('second_id', $id)->where('type', $row['value'])->select();
                    $row['list'] = $this->setThumb($row['list'], 0);
                }
                break;
        }
        return $resource;
    }


    /**
     * @param $id
     * @param $keyword
     * @param $page
     * @param $page_size
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取店铺主页
     */
    public function getShop($id, $keyword, $page, $page_size)
    {
        $ad = Db::table('zh_store_ad')->where('store_id', $id)->where('type', 1)->select() ?? [];
        if (!empty($ad)) {
            $ad = $this->setThumb($ad, 0);
        }
        $shop = Db::table('zh_store')->where('id', $id)->select()[0];
        $db = Db::table('zh_landed_property');
        if (!empty($keyword)) {
            $db->where('name', 'like', '%' . $keyword . '%');
        }
        $list = $db->where('store_id', $id)->where('status', 1)->order('create_time DESC')->limit(($page - 1) * $page_size, $page_size)->field('id,name,avg_price,thumb,region,total_amount,type,tag_id,build_surface')->select();
        if (!empty($list)) {
            foreach ($list as &$row) {
                if (!empty($row['tag_id'])) {
                    $row['tag_id'] = explode(',', $row['tag_id']);
                }
                if (!empty($row['region'])) {
                    $row['region'] = explode('/', $row['region']);
                    array_push($row['region'], '建面' . $row['build_surface'] . 'm²');
                }
            }
        }
        $list = $this->setThumb($list, 0);

        $shop_category = self::$shop_category;

        $foot_ad = Db::table('zh_store_ad')->where('store_id', $id)->where('type', 2)->select() ?? [];
        if (!empty($foot_ad)) {
            $foot_ad = $this->setThumb($foot_ad, 0);
        }

        return ['ad' => $ad, 'shop' => $shop, 'list' => $list, 'shop_category' => $shop_category, 'foot_ad' => $foot_ad];
    }


    /**
     * @param $id
     * @param int $cid
     * @param $page
     * @param $page_size
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取店铺分类
     */
    public function getShopCategory($id, $cid = 1, $page, $page_size)
    {
        $shop = Db::table('zh_store')->where('id', $id)->select()[0];
        $ad = Db::table('zh_store_ad')->where('store_id', $id)->where('type', 3)->select();
        if (!empty($ad)) {
            $ad = $this->setThumb($ad, 0);
        }
        $shop_category = self::$shop_category;
        switch ($cid) {
            case 1:
                $db = Db::table('zh_landed_property');
                $db->where('is_delete', 0)->where('store_id', $id)->order('create_time DESC')->field('id,name,avg_price as money,thumb,region');
                break;
            case 2:
                $db = Db::table('zh_landed_second_house');
                $db->where('is_delete', 0)->where('store_id', $id)->order('create_time DESC')->field('id,name,unit_price as money,thumb,region');
                break;
            case 3:
                $db = Db::table('zh_landed_renting');
                $db->where('is_delete', 0)->where('store_id', $id)->order('create_time DESC')->field('id,name,rent as money,thumb,region');
        }

        $list = $db->limit(($page - 1) * $page_size, $page_size)->select();
        $list = $this->setThumb($list);
        return ['ad' => $ad, 'shop_category' => $shop_category, 'list' => $list, 'shop' => $shop];
    }


    /**
     * @param $goods_id
     * @param $member_id
     * @param $type
     * @return bool
     * 添加我的购物车
     */
    public function addMyCar($goods_id, $member_id, $type)
    {
        $insert_data = ['member_id' => $member_id, 'goods_id' => $goods_id, 'type' => $type, 'create_time' => time(), 'update_time' => time()];
        $ret = Db::table('zh_member_cart')->insert($insert_data);
        if ($ret) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param $goods_id
     * @param $member_id
     * @param $type
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * 删除我的购物车
     */
    public function delMyCar($goods_id, $member_id, $type)
    {
        $ret = Db::table('zh_member_cart')->where('goods_id', $goods_id)->where('member_id', $member_id)->where('type', $type)->delete();
        if ($ret) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param $member_id
     * @param $page
     * @param $page_size
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取我的购物车列表
     */
    public function getMyCarList($member_id)
    {
        $list = Db::table('zh_member_cart')->where('member_id', $member_id)->select();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                switch ($value['type']) {
                    case 1:
                        $goods = Db::table('zh_landed_property')->where('id', $value['goods_id'])->field('id,name,thumb,avg_price as price,store_id')->select()[0];
                        $goods['type'] = 1;
                        break;
                    case 2:
                        $goods = Db::table('zh_landed_second_house')->where('id', $value['goods_id'])->field('id,name,thumb,unit_price as price,store_id')->select()[0];
                        $goods['type'] = 2;
                        break;
                    case 3:
                        $goods = Db::table('zh_landed_renting')->where('id', $value['goods_id'])->field('id,name,thumb,rent as price,store_id')->select()[0];
                        $goods['type'] = 3;
                        break;
                }
                $carList[$key] = $goods;
            }
        }
        if (!empty($carList)) {
            $carList = $this->setThumb($carList, 0);
            foreach ($carList as $k => $v) {
                $shop = Db::table('zh_store')->where('id', $v['store_id'])->field('id as shopid,name,logo')->select()[0];
//                $shop['logo'] = 'http://'.$_SERVER['HTTP_HOST'].'/'.$shop['logo'];
                $shop['logo'] = 'http://yijiahoutai.40b876.cn/yijia_store_admin/public' . $shop['logo'];
                $res[$v['store_id']]['shop'] = $shop;
                $res[$v['store_id']]['goods'][] = $v;
            }
        }
        $res = array_values($res);

        return $res;
    }


    /**
     * @param $member_id
     * @param $type
     * @param $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 在线预约
     */
    public function getReserve($member_id, $type, $id)
    {
        if ($type == 1) {
            $property = Db::table('zh_landed_property')->where('id', $id)->field('id,store_id,name,avg_price')->select()[0];
            $vrData = Db::table('zh_landed_property_resource')->where('propertie_id', $id)->where('type', 1)->select();
            $vrData = $this->setThumb($vrData, 0);
            $floor = Db::table('zh_landed_property_floor')->where('landed_id', $id)->group('build_num')->order('build_num', 'ASC')->field('id,landed_id,build_num')->select();
            if (!empty($floor)) {
                foreach ($floor as &$row) {
                    $row['room'] = Db::table('zh_landed_property_floor')->where('build_num', $row['build_num'])->where('landed_id', $row['landed_id'])->select();
                }
            }
            $renovation = Db::table('zh_landed_renovation')->where('store_id',$property['store_id'])->where('property_id',$property['id'])->where('pid',0)->select();
            if(!empty($renovation)){
                foreach ($renovation as &$row){
                    $row['child'] = Db::table('zh_landed_renovation')
                        ->alias('r')
                        ->join('zh_landed_renovation_detail d', 'r.id = d.renovation_id')
                        ->where('r.store_id',$property['store_id'])
                        ->where('r.pid',$row['id'])
                        ->select();
                }
            }
            $data['renovation'] = $renovation;
            $data['vr'] = $vrData;
            $data['room'] = $floor;
            $data['shop'] = $property;
            return $data;
        }elseif ($type == 2){
            $property = Db::table('zh_landed_second_house')->where('id', $id)->select()[0];
            $vrData = Db::table('zh_landed_second_house_resource')->where('second_id', $id)->where('type', 5)->select();
            $vrData = $this->setThumb($vrData, 0);
            $data['vr'] = $vrData;
            $data['shop'] = $property;
        }
        return $data;
    }


    /**
     * @param $id
     * @param $member_id
     * @param $type
     * @param $fromcar
     * @param $paytype
     * @param $floor_id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 预创建订单
     */
    public function createOrder($goods_id, $member_id, $type, $floor_id = 0,$fromcart = 0)
    {
        $goods = (object)[];
        $totalprice = 0.00;
        switch ($type) {
            case 1:
                $goods = Db::table('zh_landed_property')->where('id', $goods_id)->field('id,name,thumb,total_amount as price,store_id')->select();
                if (!empty($goods)) {
                    $goods = $goods[0];
                    if (!empty($floor_id)) {
                        $floor = Db::table('zh_landed_property_floor')->where('id', $floor_id)->select();
                    } else {
                        $floor = Db::table('zh_landed_property_floor')->where('landed_id', $goods_id)->limit(1)->select();
                    }
                    if (!empty($floor)) {
                        $floor = $floor[0];
                        $goods['price'] = $floor['total_price'];
                    } else {
                        $goods['price'] *= 10000;
                    }
                }
                $goods['type'] = 1;
                $goods['floor_id'] = !empty($floor) ? $floor['id'] : 0;
                $goods['discount_price'] = !empty($floor) ? $floor['discount_price'] : 0;
                $totalprice = !empty($floor) ? $floor['total_price'] - $floor['discount_price'] : $goods['price'];
                break;
            case 2:
                $goods = Db::table('zh_landed_second_house')->where('id', $goods_id)->field('id,name,thumb,total_amount as price,store_id')->select();
                if (!empty($goods)) {
                    $goods = $goods[0];
                    $goods['type'] = 2;
                    $goods['price'] *= 10000;
                    $totalprice = $goods['price'];
                }
                break;
            case 3:
                $goods = Db::table('zh_landed_renting')->where('id', $goods_id)->field('id,store_id,name,water_fee,electric_fee,property_fee,gas_fee,rent as price')->select();
                if (!empty($goods)) {
                    $goods = $goods[0];
                    $goods['type'] = 3;
                    $goods['cash_pledge'] = $goods['price'] * 2;
                    $totalprice = $goods['price'] + $goods['cash_pledge'];
                }
                break;
        }
        $res['goods'] = $goods;
        $res['totalprice'] = $totalprice;
        return $res;
    }


    /**
     * @param $goods_id
     * @param $member_id
     * @param $type
     * @param $paytype
     * @param $floor_id
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 提交订单
     */
    public function submitOrder($goods_id, $member_id, $type, $paytype, $buy_type, $stages, $floor_id = 0, $ip = 0,$fromcart = 0)
    {

        $member = Db::table('zh_members')->where('member_id', $member_id)->select()[0];
        Db::startTrans();
        try {
            $goods = $this->createOrder($goods_id, $member_id, $type, $floor_id);
            switch ($type) {
                case 1:
                    $order['floor_id'] = $goods['goods']['floor_id'];
                    $order['property_id'] = $goods['goods']['id'];
                    $order['discount_price'] = $goods['goods']['discount_price'];
                    $db = Db::table('zh_landed_property_order');
                    break;
                case 2:
                    $order['second_id'] = $goods['goods']['id'];

                    $db = Db::table('zh_landed_second_order');
                    break;
                case 3:
                    $order['renting_id'] = $goods['goods']['id'];
                    $order['cash_pledge'] = $goods['goods']['cash_pledge'];
                    $db = Db::table('zh_landed_renting_order');
                    break;
            }
            if (!empty($buy_type) && ($buy_type == 2 || $buy_type == 3) && !empty($stages)) {
                $goods['totalprice'] = $goods['totalprice'] / $stages;
            }
            $order['order_sn'] = $this->createNO('YJ');
            $order['store_id'] = $goods['goods']['store_id'];
            $order['total_amount'] = $goods['goods']['price'];
            $order['pay_amount'] = $goods['totalprice'];
            $order['buy_type'] = $buy_type;
            $order['stages'] = $stages ?? 0;
            $order['pay_type'] = $paytype;
            $order['status'] = 0;
            $order['create_time'] = time();
            $order['member_id'] = $member_id;
            $orderOk = $db->insert($order);
            if (!$orderOk) {
                Db::rollback();
                exception('创建订单失败');
            } else {
                $orderid = $db->getLastInsID();
            }
            $paymemt = [];
            if ($paytype == 1) {
                //微信支付
                $params['title'] = $goods['goods']['name'];
                $params['tid'] = $order['order_sn'];
                $params['fee'] = $order['pay_amount'];
                $params['ip'] = $ip;
                $params['type'] = $type;
                $params['notify_url'] = 'http://yijiazhihui.40b876.cn/landed/getWxPayNotify';
                $res = Payment::getWxAppPay($params);
                if (is_array($res)) {
                    $paymemt['orderString'] = json_encode($res);
                } else {
                    Db::rollback();
                }
            } elseif ($paytype == 2) {
                //支付宝支付
                $params['title'] = $goods['goods']['name'];
                $params['tid'] = $order['order_sn'];
//                $params['fee'] = $order['pay_amount'];
                $params['fee'] = 0.01;
                $params['type'] = $type;
                $params['notify_url'] = 'http://yijiazhihui.40b876.cn/landed/getAliPayNotify';
                $res = Payment::getAliPay($params);
                if($res){
                    $paymemt['orderString'] = $res;
                }else{
                    Db::rollback();
                }
            } elseif ($paytype == 3) {
                //金币支付
                if ($member['gold'] < $goods['totalprice']) {
                    Db::rollback();
                    exception('金币不足');
                }
                $memberOk = Db::table('zh_members')->where('member_id', $member_id)->update(['gold' => $member['gold'] - $goods['totalprice']]);
                if (!$memberOk) {
                    Db::rollback();
                    exception('更新用户金币失败');
                }
                $orderOk = $db->where('id', $orderid)->update(['status' => 2, 'update_time' => time(), 'pay_time' => time()]);
                if (!$orderOk) {
                    Db::rollback();
                    exception('更新订单状态失败');
                }
            } else {
                //钱包支付
                if ($member['account'] < $goods['totalprice']) {
                    Db::rollback();
                    exception('余额不足');
                }
                $memberOk = Db::table('zh_members')->where('member_id', $member_id)->update(['account' => $member['account'] - $goods['totalprice']]);
                if (!$memberOk) {
                    Db::rollback();
                    exception('更新账户余额失败');
                }
                $orderOk = $db->where('id', $orderid)->update(['status' => 2, 'update_time' => time()]);
                if (!$orderOk) {
                    Db::rollback();
                    exception('更新订单支付状态失败');
                }
            }
            if(!empty($fromcart)){
                Db::table('zh_member_cart')->where('member_id', $member_id)->where('goods_id',$goods_id)->where('type',$type)->delete();
            }
            Db::commit();
            return ['status' => 1, 'paymemt' => $paymemt, 'orderinfo' => $paymemt['orderString'],'order'=>$order];
        } catch (\Exception $e) {
            Db::rollback();
            return ['status' => 0, 'msg' => $e->getMessage()];
        }
    }


    /**
     * @param $orderdata
     * @param $type
     * @param $orderid
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * 回调更新订单数据
     */
    public function getWxPayNotify($orderdata,$type,$orderid)
    {
        switch ($type)
        {
            case 1:
                $db = Db::table('zh_landed_property_order');
                break;
            case 2:
                $db = Db::table('zh_landed_second_order');
                break;
            case 3:
                $db = Db::table('zh_landed_renting_order');
                break;
        }
        $orderUpdate = $db->where('id',$orderid)->update($orderdata);
        if($orderUpdate){
            return true;
        }else{
            return false;
        }
    }


    /**
     * @param $table
     * @param $field
     * @param $prefix
     * @return stringc
     * 创建订单编号
     */
    public function createNO($prefix)
    {
        $billno = date('YmdHis') . rand('100000', '999999');
        $order_sn = $prefix . $billno;
        return $order_sn;
    }


    /**
     *
     * 处理图片
     */
    public function setThumb($thumbs = [], $is_ad = 1)
    {
        if (!empty($thumbs) && is_array($thumbs)) {
            foreach ($thumbs as $key => &$value) {
                if (isset($value['thumb']) && !empty($value['thumb'])) {
//                    $value['thumb'] = 'http://'.$_SERVER['HTTP_HOST'].'/'.$value['thumb'];
                    if (isset($value['type']) && $is_ad == 1) {
                        $value['ad_type'] = self::$ad_type[$value['type']];
                        $value['thumb'] = 'http://yijiahoutai.40b876.cn/yijia_admin/public' . $value['thumb'];
                    } else {
                        $value['thumb'] = 'http://yijiahoutai.40b876.cn/yijia_store_admin/public' . $value['thumb'];
                    }
                }
                if (isset($value['logo']) && !empty($value['logo'])) {
//                    $value['logo'] = 'http://'.$_SERVER['HTTP_HOST'].'/'.$value['logo'];
                    $value['logo'] = 'http://yijiahoutai.40b876.cn/yijia_store_admin/public' . $value['logo'];
                }
//                if(isset($value['resource_url']) && !empty($value['resource_url'])){
//
//                    $value['resource_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/'.$value['resource_url'];
//                }
            }
        }
        return $thumbs;
    }

    /**
     * @param $city
     * 获取当前城市所有区域
     */
    public function getArea($city)
    {
        $sql = "select a1.*,a2.name as city from zh_area as a1 join (select * from zh_area where name like '%{$city}%') as a2 on a1.pid = a2.id";
        $list = Db::query($sql);
        return $list;
    }

    /**
     * @param $city
     * 获取当前城市所有地铁信息
     */
    public function getMetroStation($city)
    {
        $list = Db::table('zh_metro_city')
            ->alias('c')
            ->join('zh_metro_line l', 'c.id = l.city_id')
//            ->join('zh_metro_station s','l.id = s.line_id')
            ->where('c.name', 'like', '%' . $city . '%')
            ->field('c.name as city_name,c.id as city_id,l.name as line_name,l.id as line_id')
            ->select();

        if (!empty($list)) {
            foreach ($list as &$row) {
                $row['list'] = Db::table('zh_metro_station')->where('line_id', $row['line_id'])->field('name as station_name,id as station_id')->select();
            }
        }
        return $list;
    }


    /**
     * @param $lat1
     * @param $lng1
     * @param $lat2
     * @param $lng2
     * @param int $len_type
     * @param int $decimal
     * @return float
     * 计算距离
     */
    public function GetDistance($lat1, $lng1, $lat2, $lng2, $len_type = 1, $decimal = 2)
    {
        // echo "string";
        $pi = 3.1415926000000001;
        $er = 6378.1369999999997;
        $radLat1 = ($lat1 * $pi) / 180;
        $radLat2 = ($lat2 * $pi) / 180;
        $a = $radLat1 - $radLat2;
        $b = (($lng1 * $pi) / 180) - (($lng2 * $pi) / 180);
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + (cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))));
        $s = $s * $er;
        $s = round($s * 1000);
        if (1 < $len_type) {
            $s /= 1000;
        }
        return round($s, $decimal);
    }


    /**
     * @param $region
     * @param $address
     * @return bool|mixed
     * 获取经纬度
     */
    public function getLatLng($region, $address)
    {
        $address = trim(str_replace('/', '', $region . $address));
        $map_api = "https://restapi.amap.com/v3/geocode/geo?address=" . $address . "&output=json&key=" . self::$map_api_key;
        $api_res = file_get_contents($map_api);
        if (!empty($api_res)) {
            $res_latlng = json_decode($api_res, true);
            $res_latlng = $res_latlng['geocodes'][0]['location'];
            return $res_latlng;
//            $res_latlng = explode(',', $res_latlng);
        } else {
            return false;
        }
    }


    /**
     * @param $keyword
     * @param $latlng
     * @return array
     * 获取周边信息
     */
    public function getAround($keyword, $latlng)
    {
        $map_api = "https://restapi.amap.com/v3/place/around?key=" . self::$map_api_key . "&location=" . $latlng . "&radius=10000&keywords=" . $keyword . "&extensions=base&offset=5";
        $api_res = file_get_contents($map_api);
        $api_res = json_decode($api_res, true);
        $res = [];
        if (!empty($api_res['pois'])) {
            $list = $api_res['pois'];
            foreach ($list as $k => $v) {

                $res[$k]['name'] = $v['name'];
                $res[$k]['type'] = $v['type'];
                $res[$k]['address'] = $v['address'];
                $res[$k]['distance'] = $v['distance'];
                $location = explode(',', $v['location']);
                $res[$k]['latitude'] = $location[0];
                $res[$k]['longitude'] = $location[1];
            }
        }
        return $res;
    }


    /**
     * @param $ordersn
     * @param $type
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 根据订单号获取订单
     */
    public function getOneOrder($ordersn,$type)
    {
        switch ($type)
        {
            case 1:
                $db = Db::table('zh_landed_property_order');
                break;
            case 2:
                $db = Db::table('zh_landed_second_order');
                break;
            case 3:
                $db = Db::table('zh_landed_renting_order');
                break;
        }
        $res = $db->where('order_sn',$ordersn)->select();

        return !empty($res) ? $res[0] : [];

    }


    /**
     * @param $member_id
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取我的申请商家
     */
    public function getApplyShop($member_id)
    {
        $res = Db::table('zh_store_apply')->where('member_id',$member_id)->select();
        return $res ? $res[0] : [] ;
    }


    /**
     * @param $member_id
     * @param $param
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 设置我的申请
     */
    public function setApplyShop($member_id,$param)
    {
        $res = $this->getApplyShop($member_id);
        if(!empty($res)){
            Db::table('zh_store_apply')->where('member_id',$member_id)->update($param);
        }else{
            Db::table('zh_store_apply')->insert($param);
        }
        return true;
    }


    /**
     * @param $member_id
     * @param $param
     * @return bool
     * 添加评论
     */
    public function addComment($member_id,$param)
    {
        if(!$member_id){
            return false;
        }
        $ret = Db::table('zh_landed_comment')->insert($param);
        if($ret){
            return $ret;
        }else{
            return false;
        }
    }

    /**
     * @param $type
     * @param $goods_id
     * @return array
     * 获取评论列表
     */
    public function getCommentList($type,$goods_id,$limit,$member_id=0)
    {
        if(empty($limit)){
            $limit = 100;
        }
        $list = Db::table('zh_landed_comment')
            ->alias('c')
            ->join('zh_members m', 'c.member_id = m.member_id')
            ->where('c.goods_id',$goods_id)
            ->where('c.type',$type)
            ->where('c.pid',0)
            ->field('c.*,m.nickname,m.avatar')
            ->limit($limit)
            ->select();
        if(!empty($list)){
            foreach ($list as &$row){
                $commentCount = $this->getCommentStartCount($row['id']);
                $row['comment_count'] = $commentCount['comment_total'];
                $row['start_count'] = $commentCount['is_start'];
                $row['create_time'] = date("Y-m-d H:i:s",$row['create_time']);
                if(!empty($member_id)){
                    if(!empty($row['is_start'])){
                        $memberstart = explode('_',$row['is_start']);
                        $memberstart = array_values($memberstart);
                        $row['hasmember'] = in_array($member_id,$memberstart) ? 1 : 0;
                    }else{
                        $info['hasmember'] = 0;
                    }
                }else{
                    $row['hasmember'] = 0;
                }
            }
        }
        return $list ?? [];
    }


    /**
     * @param $type
     * @param $goods_id
     * @return null
     * 获取评论详情
     */
    public function getCommentInfo($comment_id,$member_id=0)
    {
        $info = Db::table('zh_landed_comment')->alias('c')->join('zh_members m', 'c.member_id = m.member_id')->where('c.id',$comment_id)->where('c.pid',0)->field('c.*,m.nickname,m.avatar')->select();
        if(!empty($info)){
            $info = $info[0];
            if(!empty($member_id)){
                if(!empty($info['is_start'])){
                    $memberstart = explode('_',$info['is_start']);
                    $memberstart = array_values($memberstart);
                    $info['hasmember'] = in_array($member_id,$memberstart) ? 1 : 0;
                }else{
                    $info['hasmember'] = 0;
                }
            }else{
                $info['hasmember'] = 0;
            }
            $commentCount = $this->getCommentStartCount($info['id']);
            $info['comment_count'] = $commentCount['comment_total'];
            $info['start_count'] = $commentCount['is_start'];
            $info['create_time'] = date("Y-m-d H:i:s",$info['create_time']);
            $info['child'] = Db::table('zh_landed_comment')->alias('c')->join('zh_members m', 'c.member_id = m.member_id')->where('c.pid',$info['id'])->field('c.*,m.nickname,m.avatar')->select();
            if(!empty($info['child'])){
                foreach ($info['child'] as &$row){
                    $childCommentCount = $this->getCommentStartCount($row['id']);
                    $row['comment_count'] = $childCommentCount['comment_total'];
                    $row['start_count'] = $childCommentCount['is_start'];
                    $row['create_time'] = date("Y-m-d H:i:s",$row['create_time']);
                    if(!empty($member_id)){
                        if(!empty($row['is_start'])){
                            $memberstart = explode('_',$row['is_start']);
                            $memberstart = array_values($memberstart);
                            $row['hasmember'] = in_array($member_id,$memberstart) ? 1 : 0;
                        }else{
                            $row['hasmember'] = 0;
                        }
                    }else{
                        $row['hasmember'] = 0;
                    }
                }
            }
        }
        return $info ? $info : null;
    }


    /**
     * @param $member_id
     * @param $comment_id
     * @param $is_start
     * @return mixed
     * 点赞
     */
    public function addStart($member_id,$comment_id,$is_start)
    {
        $comment = Db::table('zh_landed_comment')->where('id',$comment_id)->select()[0];

        if($is_start == 1){
            $ret = Db::table('zh_landed_comment')->where('id',$comment_id)->update(['is_start'=>$comment['is_start'].'_'.$member_id]);
        }else{
            if(!empty($comment['is_start'])){
                $startmember = explode('_',$comment['is_start']);
                foreach ($startmember as $k=>$v) {
                    if($v == $member_id){
                        unset($startmember[$k]);
                    }
                }
                $startmember = implode('_',$startmember);
                $ret = Db::table('zh_landed_comment')->where('id',$comment_id)->update(['is_start'=>$startmember]);
            }
        }
        return $ret;
    }


    /**
     * @param $comment_id
     * @return array
     * 获取评论数和点赞数
     */
    public function getCommentStartCount($comment_id){
        $comment = Db::table('zh_landed_comment')->where('id',$comment_id)->select();
        if(!empty($comment)){
            $comment = $comment[0];
        }
        $comment_total = Db::table('zh_landed_comment')->where('id',$comment_id)->count();
        if(!empty($comment['is_start'])){
            $is_start = explode('_',$comment['is_start']);
            $is_start = count($is_start);
        }else{
            $is_start = 0;
        }
        return ['comment_total'=>$comment_total ,'is_start'=>$is_start];
    }

    /**
     * @param $comment_id
     * @return array
     * 获取评论数和点赞数
     */
    public function getCommentStartCountByGoodsId($goodsid,$type){
        $comment = Db::table('zh_landed_comment')->where('goods_id',$goodsid)->where('type',$type)->select();
        if(!empty($comment)){
            $comment = $comment[0];
        }
        $comment_total = Db::table('zh_landed_comment')->where('goods_id',$goodsid)->where('type',$type)->count();
        if(!empty($comment['is_start'])){
            $is_start = explode('_',$comment['is_start']);
            $is_start = count($is_start);
        }else{
            $is_start = 0;
        }
        return ['comment_total'=>$comment_total ,'is_start'=>$is_start];
    }


    /**
     * @param $param
     * @return bool
     * 添加评论
     */
    public function addCollection($param)
    {
        $collection = Db::table('zh_member_collection')->where('goods_id',$param['goods_id'])->where('type',$param['type'])->where('member_id',$param['member_id'])->select();
        if(!empty($collection)){
            Db::table('zh_member_collection')->where('goods_id',$param['goods_id'])->where('type',$param['type'])->where('member_id',$param['member_id'])->update($param);
        }else{
            Db::table('zh_member_collection')->insert($param);
        }
        return true;
    }


    /**
     * @param $member_id
     * @return array
     * 获取收藏列表
     */
    public function getCollectionList($member_id)
    {
        $list = Db::table('zh_member_collection')->where('member_id', $member_id)->select();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                switch ($value['type']) {
                    case 1:
                        $goods = Db::table('zh_landed_property')->where('id', $value['goods_id'])->field('id,name,thumb,avg_price as price,store_id')->select()[0];
                        $goods['type'] = 1;
                        break;
                    case 2:
                        $goods = Db::table('zh_landed_second_house')->where('id', $value['goods_id'])->field('id,name,thumb,unit_price as price,store_id')->select()[0];
                        $goods['type'] = 2;
                        break;
                    case 3:
                        $goods = Db::table('zh_landed_renting')->where('id', $value['goods_id'])->field('id,name,thumb,rent as price,store_id')->select()[0];
                        $goods['type'] = 3;
                        break;
                }
                $carList[$key] = $goods;
                $carList[$key]['collection_id'] = $value['id'];
            }
        }
        if (!empty($carList)) {
            $carList = $this->setThumb($carList, 0);
        }
        return $carList;
    }

    /**
     * @param $ids
     * @param $member_id
     * @return bool
     * 批量删除
     */
    public function delCollection($ids,$member_id)
    {
        $ids = explode(',',$ids);
        if(is_array($ids)){
            foreach ($ids as $k=>$v){
                Db::table('zh_member_collection')->where('id',$v)->where('member_id',$member_id)->update(['is_deleted'=>1]);
            }
        }
        return true;
    }


}